package PrjHttpUtils

import (
	"net/http"
	"regexp"
	_ "regexp"
	"strings"
)

type FilterMatchType byte

const (
	FMT_EQ       FilterMatchType = iota // 等于
	FMT_PREFIX                          // 开头
	FMT_CONTAINS                        // 包含
	FMT_REGEX                           // 正则匹配
)

type filter_rec struct {
	matchuri  string
	matchtype FilterMatchType
	handler   func(rw http.ResponseWriter, r *http.Request) bool
}

func (this *filter_rec) IsMatch(uri string) bool {
	switch this.matchtype {
	case FMT_EQ:
		return this.matchuri == uri
	case FMT_PREFIX:
		return strings.HasPrefix(uri, this.matchuri)
	case FMT_CONTAINS:
		return strings.Contains(uri, this.matchuri)
	case FMT_REGEX:
		ok, _ := regexp.MatchString(this.matchuri, uri)
		return ok
	}
	return false
}

// 保证有序uri
var filter_array = make([]*filter_rec, 0)

/*
*

	注册过滤器
*/
func RegisterWebFilter(uriRule string, matchType FilterMatchType, fn func(rw http.ResponseWriter, r *http.Request) bool) {
	rec := &filter_rec{
		matchuri:  uriRule,
		matchtype: matchType,
		handler:   fn,
	}
	filter_array = append(filter_array, rec)
}

func WrapHandle(handler func(rw http.ResponseWriter, r *http.Request)) func(rw http.ResponseWriter, r *http.Request) {

	return func(rw http.ResponseWriter, r *http.Request) {
		var uri = r.RequestURI
		for _, rec := range filter_array {
			if rec.IsMatch(uri) {
				if !rec.handler(rw, r) {
					return
				}
			}
		}
		handler(rw, r)
	}
}

func HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
	http.HandleFunc(pattern, WrapHandle(handler))
}
